package com.imufe.springbootshiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @Auther: sunYong
 * @Date: 2019/2/7 21:36
 * @Description: ${package_name}
 */
@Controller
public class UserController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello world";
    }

    @RequestMapping("/add")
    public String add(){
        return "/user/add";
    }

    @RequestMapping("/update")
    public String update(){
        return "/user/update";
    }

    @RequestMapping("/login")
    public String login(){
        return "/login";
    }
    @RequestMapping("/noAuth")
    public String noAuth(){
        return "/noAuth";
    }
    /*登录逻辑*/
    @RequestMapping("/toLogin")
    public String toLogin(String username,String password,Model model){
        /*使用Shiro编写认证操作*/
//        1、获取Subject
        Subject subject = SecurityUtils.getSubject();
//        2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
//        3、执行登录方法
        try {
            subject.login(token);//登陆成功
//            跳转到test.html
            return "redirect:/testThymeLeaf";
        }
            catch (UnknownAccountException e){
            model.addAttribute("msg","用户名不存在");
               System.out.println("登录失败1");
            return "login";
            //登录失败,用户名不存在
        }
        catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不存在");
            System.out.println("登录失败2");
            return "login";
            //登录失败,密码错误
        }
    }
@RequestMapping("/testThymeLeaf")
    public String testThymeLeaf(Model model){
        model.addAttribute("name","test");
        return "/test";
    }
}
